import printJS from 'print-js'
import html2canvas from 'html2canvas'

function createWatermark(el, watermarkConfig, watermarkCanvas) {
  const { font, color, opacity, printElWidth, printElHeight, watermarkElWidth, watermarkElHeight } =
    watermarkConfig
  const canvas = document.createElement('canvas')
  const scaleX = printElWidth / el.width
  const scaleY = printElHeight / el.height
  canvas.width = printElWidth
  canvas.height = printElHeight
  const ctx = canvas.getContext('2d')
  ctx.scale(scaleX, scaleY)
  ctx.drawImage(el, 0, 0)
  ctx.font = font
  ctx.fillStyle = color
  ctx.filter = `opacity(${opacity})`
  // 移动中心点
  ctx.translate(printElWidth / 2, printElHeight / 2)
  // ctx.re
  ctx.rotate((-45 * Math.PI) / 180)
  ctx.translate(-printElWidth * 2, -printElHeight)

  for (let x = 0; x <= printElWidth / watermarkElWidth + 100; x++) {
    for (let y = 0; y <= printElHeight / watermarkElHeight + 100; y++) {
      ctx.drawImage(
        watermarkCanvas,
        x * (watermarkElWidth / scaleX + 50),
        y * (watermarkElHeight / scaleY + 50),
        watermarkElWidth / scaleX,
        watermarkElHeight / scaleY
      )
    }
  }
  return canvas
}

export async function onPrint(el, watermarkConfig) {
  const printEl = document.querySelector(el)
  const canvasEl = await html2canvas(printEl, {
    width: printEl.offsetWidth,
    height: printEl.offsetHeight,
    useCORS: true
  })
  const watermarkEl = document.createElement('div')
  watermarkEl.innerHTML = watermarkConfig.watermark
  watermarkEl.style = 'width: fit-content;'
  document.body.appendChild(watermarkEl)
  const watermarkCanvas = await html2canvas(watermarkEl, {
    useCORS: true,
    width: watermarkEl.offsetWidth,
    height: watermarkEl.offsetHeight,
    backgroundColor: null
  })
  const newCanvas = await createWatermark(
    canvasEl,
    {
      ...watermarkConfig,
      printElWidth: printEl.offsetWidth,
      printElHeight: printEl.offsetHeight,
      watermarkElWidth: watermarkEl.offsetWidth,
      watermarkElHeight: watermarkEl.offsetHeight
    },
    watermarkCanvas
  )
  printJS({
    type: 'image',
    printable: newCanvas.toDataURL('image/png'),
    header: watermarkConfig.header
  })
  document.body.removeChild(watermarkEl)
}
